import config from '../../build/config'
import store from '@/store'
import MsgUtil from "./msgUtils";
// 初始化，创建jim长连接

const JIM = {}
JIM.open = function(userName, passWord) {
  // 如果输入的账号密码为空 从localstorage 拿
  if (userName === '' || passWord === '') {
    const loginInfo = JSON.parse(localStorage.getItem('imLoginInfo'))
    userName = loginInfo.imUserName
    passWord = loginInfo.imPassWord
  }
  if (userName) {
    JIM.conn = new WebSocket( config.imPath + '?username=' + userName + '&password=' + passWord)
    JIM.conn.addEventListener('open', function(e) {
      if (e.isTrusted) { // 说明连接打开来了
        console.log('open', JSON.stringify(e))
        /**
         * 本地缓存登录信息
         */
        localStorage.setItem('imUserName', userName)// 此处为imId
        localStorage.setItem('imPassWord', passWord)
      }
    })
    JIM.conn.addEventListener('message', function(event) {
      console.log('Message from server ', event.data)
      const resp = JSON.parse(event.data)
      if (resp.command === 9) { // 登录信息处理
        localStorage.setItem('imLoginInfo', JSON.stringify(event.data))
        JIM.getGroupAndFriendList()
      }
      if (resp.command === 18) { // 获取到群组好友列表,个人基本信息推送
        store.commit('updateGroupAndFriendList', {
          data: resp.data
        })
      }
      if (resp.command === 10) { // 离开群聊
        store.commit('removeFromGroup', {
          data: resp.data
        })
       MsgUtil.sendWarn( resp.data.user.nick + '退出群聊...')
      }
      if (resp.command === 11) { // 收到消息
        store.commit('updateMsg', {
          data: resp.data
        })
      }
      if (resp.command === 9) { // 加入群聊
        MsgUtil.sendSuccess( resp.user.nick + '加入群聊...')
      }
    })
  }
}
// 断开连接
// eslint-disable-next-line no-unused-vars
JIM.close = function() {
  JIM.conn.close()
  /**
   * 清除缓存
   */
  localStorage.removeItem('imUserName')
  localStorage.removeItem('imPassWord')
  localStorage.removeItem('imLoginInfo')

  /**
   * 服务器端关闭
   */
  // {
  //   "cmd":"命令码(14)int类型",
  //   "userid":"用户id"
  // }
}

/**
 *  获取好友/群组类表
 */
JIM.getGroupAndFriendList = function() {
  const msg = {
    cmd: 17,
    type: 0,
    userId: localStorage.getItem('imUserName')
  }
  JIM.send(JSON.stringify(msg))
}

// 消息发送
JIM.send = function(msgObj) {
  try {
    JIM.conn.send(msgObj, function() {
    })
  } catch (e) {
    console.log(JSON.stringify(e))
    return false
  }
  return true
}




export default JIM
